package com.ww.springboot.boot.algorithm.leetcode1;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-03-11 17:57
 */
public class AM61旋转链表 {


    public static void main(String[] args) {
        ListNode listNode = new ListNode(1,new ListNode(2,new ListNode(3,null)));
        System.out.println(rotateRight(listNode, 2000000000));
    }

    public static ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null){
            return head;
        }
        int n = 1;
        ListNode headCopy = head;
        while (headCopy.next != null){
            headCopy = headCopy.next;
            n++;
        }
        k = k%n;
        for (int i = 0; i < k; i++) {
            head = rotateRight(head);
        }
        return head;
    }

    public static ListNode rotateRight(ListNode head) {
        ListNode listNode = new ListNode(0,head);
        //全体往右移动 其实只需要将尾节点变为头结点即可
        while (head.next.next != null){
            head = head.next;
        }
        listNode.val = head.next.val;
        head.next = null;
        return listNode;
    }



    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
